﻿namespace MSHelpMe
{
    using System;
    using System.ComponentModel;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Navigation;
    using BingService;
    using Microsoft.Phone.Shell;
    using Microsoft.Phone.Tasks;
    using ViewModels;

    public partial class MainPage
    {
        private readonly BingPortTypeClient searchClient = new BingPortTypeClient();

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            DataContext = App.ViewModel;

            this.searchClient.SearchCompleted +=
                (obj, arg) =>
                {
                    if (arg.Error != null)
                    {
                        this.Dispatcher.BeginInvoke(() => ShowLoading(false, string.Empty));
                        MessageBox.Show("Connect failed. Please check your network and try later.");
                    }
                    else
                    {
                        this.Dispatcher.BeginInvoke(
                            () =>
                            {
                                App.ViewModel.TotalSearched++;
                                ShowLoading(false, string.Empty);

                                if (!App.ViewModel.AppendSearchResult(arg.Result))
                                {
                                    MessageBox.Show(
                                        "No results where found. Please change your search criteria and try again.");
                                    pivot.SelectedIndex = 0;
                                }
                                else
                                {
                                    PromptVote();
                                }
                            });
                    }
                };

#if DEBUG
            Application.Current.Host.Settings.EnableFrameRateCounter = false;

            // Avoid screen locks while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }
#endif
        }

        private static void PromptVote()
        {
            if (!App.ViewModel.NotVoted)
            {
                return;
            }

            if (App.ViewModel.TotalSearched == 3
                || App.ViewModel.TotalSearched == 10
                || App.ViewModel.TotalSearched == 20
                || App.ViewModel.TotalSearched == 50
                || App.ViewModel.TotalSearched % 100 == 0)
            {
                var r = MessageBox.Show("Do you like this app? If you do, please vote it.", "Vote Me",
                                        MessageBoxButton.OKCancel);

                if (r == MessageBoxResult.OK || r == MessageBoxResult.Yes)
                {
                    var task = new MarketplaceReviewTask();
                    task.Show();
                    App.ViewModel.NotVoted = false;
                }
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(App.ViewModel.QueryText))
            {
                this.Dispatcher.BeginInvoke(() => txtSearchText.Text = App.ViewModel.QueryText);
            }

            base.OnNavigatedTo(e);
        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray.IsVisible = true;
        }

        private static void ShowLoading(bool show, string text)
        {
            if (show && !SystemTray.IsVisible)
            {
                SystemTray.IsVisible = true;
            }

            if (SystemTray.ProgressIndicator == null)
            {
                SystemTray.ProgressIndicator = new ProgressIndicator();
            }

            SystemTray.ProgressIndicator.Text = text;
            SystemTray.ProgressIndicator.IsVisible = show;
            SystemTray.ProgressIndicator.IsIndeterminate = show;
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            this.Focus();
            App.ViewModel.ClearSearchResults();
            pivot.SelectedIndex = 1;

            this.Dispatcher.BeginInvoke(() => ShowLoading(true, "Searching..."));

            var searchRequest = new SearchRequest
                                    {
                                        AppId = "[Bing ID]",
                                        Sources = new[] { SourceType.Web, SourceType.Spell },
                                        Query = CreateQuery(txtSearchText.Text)
                                    };


            var webRequest = new WebRequest { Count = 50, CountSpecified = true, Offset = 0, OffsetSpecified = true };

            searchRequest.Web = webRequest;
            this.searchClient.SearchAsync(searchRequest);
        }

        private static string CreateQuery(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return string.Empty;
            }

            const string pattern = "{0} (site:support.microsoft.com" +
                                   " OR site:msdn.microsoft.com" +
                                   " OR site:technet.microsoft.com" +
                                   " OR site:office.microsoft.com" +
                                   " OR site:blogs.office.com" +
                                   " OR site:windows.microsoft.com" +
                                   " OR site:windowsteamblog.com" +
                                   " OR site:zune.net" +
                                   " OR site:support.xbox.com" +
                                   " OR site:answers.microsoft.com" +
                                   " OR site:microsoft.com" +
                                   ")";
            return string.Format(pattern, text);
        }

        private void BrowseButtonClick(object sender, GestureEventArgs e)
        {
            e.Handled = true;
            var button = sender as Grid;

            if (button == null)
            {
                return;
            }

            new WebBrowserTask
                {
                    Uri = new Uri(button.Tag.ToString())
                }.Show();
        }

        private void FlagButtonClick(object sender, GestureEventArgs e)
        {
            e.Handled = true;
            var button = sender as Grid;

            if (button == null)
            {
                return;
            }

            App.ViewModel.FlagItem(button.Tag as ItemViewModel);
        }

        private void UnflagButtonClick(object sender, GestureEventArgs e)
        {
            e.Handled = true;
            var button = sender as Grid;

            if (button == null)
            {
                return;
            }

            App.ViewModel.UnflagItem(button.Tag as ItemViewModel);
        }

        private void txtSearchText_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && !string.IsNullOrWhiteSpace(txtSearchText.Text))
            {
                btnSearch_Click(sender, null);
            }
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            txtSearchText.Text = string.Empty;
            txtSearchText.Focus();
        }

        private void btnTakePicture_Click(object sender, RoutedEventArgs e)
        {
            this.GotoPhotoPage();
        }

        private void GotoPhotoPage()
        {
            NavigationService.Navigate(new Uri("/PhotoCapture.xaml", UriKind.Relative));
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, CancelEventArgs e)
        {
            if (pivot.SelectedIndex > 0)
            {
                pivot.SelectedIndex--;
                e.Cancel = true;
            }
        }

        private void Grid_Tap(object sender, GestureEventArgs e)
        {
            this.BrowseButtonClick(sender, e);
        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ApplicationBar.IsVisible = pivot.SelectedIndex == 0;
        }

        private void menuAbout_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/About.xaml", UriKind.Relative));
        }

        private void txtSearchText_TextChanged(object sender, TextChangedEventArgs e)
        {
            btnSearch.IsEnabled = !string.IsNullOrWhiteSpace(txtSearchText.Text);
        }

        private void txtSearchText_GotFocus(object sender, RoutedEventArgs e)
        {
            txtSearchText.SelectAll();
        }
    }
}